package com.visionet.school.app.web.service;

import com.visionet.school.app.web.common.utils.PageUtils;
import com.visionet.school.app.web.common.web.WebContextFactory;
import com.visionet.school.app.web.entity.member.Member;
import com.visionet.school.app.web.entity.msg.Msg;
import com.visionet.school.app.web.entity.msg.vo.MsgVo;
import com.visionet.school.app.web.entity.vo.LoginAccountVo;
import com.visionet.school.app.web.repository.file.FileClassRepository;
import com.visionet.school.app.web.repository.member.MemberClassRepository;
import com.visionet.school.app.web.repository.member.MemberFileRepository;
import com.visionet.school.app.web.repository.member.MemberRepository;
import com.visionet.school.app.web.repository.msg.MsgRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by hxpeng on 2017/3/7.
 */
@Service
public class MsgService {

    private static final Logger logger = LoggerFactory.getLogger(MsgService.class);

    @Resource
    private MsgRepository msgRepository;

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberClassRepository memberClassRepository;

    @Resource
    private FileClassRepository fileClassRepository;

    @Resource
    private MemberFileRepository memberFileRepository;

    public void save(MsgVo msgVo){
        try {
            LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();
            String loginAccountMemberId = loginAccountVo.getMemberId();

            //批量提交留言
            for(String s : msgVo.getStudentIds()){
                Member student = memberRepository.findOne(s);
                if(student == null){
                    throw new RuntimeException("未找到留言对象哦！");
                }
                Msg msg = new Msg();
                BeanUtils.copyProperties(msgVo,msg);
                msg.setMemberId(loginAccountMemberId);
                msg.setMemberName(loginAccountVo.getMemberName());
                msg.setToMemberId(student.getId());
                msg.setToMemberName(student.getMemberName());
                msg.setIsDeleted("0");
                msgRepository.save(msg);
            }

//            Member student = memberRepository.findOne(msgVo.getToMemberId());
//            if(student == null){
//                throw new RuntimeException("未找到留言对象哦！");
//            }
//            Msg msg = new Msg();
//            BeanUtils.copyProperties(msgVo,msg);
//            msg.setMemberId(loginAccountMemberId);
//            msg.setMemberName(loginAccountVo.getMemberName());
//            msg.setToMemberId(student.getId());
//            msg.setToMemberName(student.getMemberName());
//            msg.setIsDeleted("0");

//            if(msgVo.getMsgType().equals(FileEnums.AUDIO.toKey())){
//                //下载音频
//                StringBuffer stringBuffer = new StringBuffer(PropsUtil.getProperty(PropsKeys.SERVER_AUDIO_PATH));
//                stringBuffer.append("/").append(loginAccountMemberId);
//                stringBuffer.append("_").append(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//                FileVo fileVo = DownLoadFileUtils.downloadWechatFile(msgVo.getMediaId(),stringBuffer.toString(),false, FileEnums.AUDIO.toKey());
//                //保存文件
//                FileClass fileClass = new FileClass();
//                BeanUtils.copyProperties(fileVo,fileClass);
//                fileClass.setIsDeleted("0");
//                fileClass = fileClassRepository.save(fileClass);
//                MemberFile memberFile = new MemberFile();
//                memberFile.setMemberId(loginAccountMemberId);
//                memberFile.setFileId(fileClass.getId());
//                memberFile.setIsDeleted("0");
//                memberFileRepository.save(memberFile);
//                msg.setMsgAudioPath(fileVo.getFilePath());
//            }
//            msgRepository.save(msg);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("保存留言失败");
        }
    }

    public Map<String, Object> getMsgPage(final MsgVo msgVo, String sortType){
        Sort s = new Sort(Sort.Direction.DESC, sortType);
        Pageable pageable = PageUtils.buildPageRequest(msgVo.getPageInfo().getPageNumber(), msgVo.getPageInfo().getPageSize(), s);
        Page<Msg> objPage = msgRepository.findAll(new Specification<Msg>() {
            public Predicate toPredicate(Root<Msg> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> lstPredicates = new ArrayList<Predicate>();
                List<String> studentIds = msgVo.getStudentIds();
                if (studentIds != null && studentIds.size() > 0) {
                    Expression<String> exp = root.get("toMemberId");
                    lstPredicates.add(exp.in(studentIds));
                }

                if (StringUtils.isNotBlank(msgVo.getMemberId())) {
                    lstPredicates.add(cb.equal(root.get("memberId"), msgVo.getMemberId()));
                }
                lstPredicates.add(cb.equal(root.get("isDeleted"), "0"));
                Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
                return cb.and(lstPredicates.toArray(arrayPredicates));
            }
        }, pageable);
        return PageUtils.getPageMap(objPage);
    }
}
